<template>
	<view class="update-popup" v-if="showUpdate">
		<view class="popup-content">
			<view class="popup-header">
				<text class="popup-title">{{ showProgress ? '下载中...' : '发现新版本' }}</text>
			</view>
			<view class="popup-body">
				<!-- 版本信息 -->
				<view class="version-info" v-if="!showProgress">
					<text>当前版本: {{ realCurrentVersion }}</text>
					<text>最新版本: {{ latestVersion }}</text>
				</view>
				<!-- 更新描述 -->
				<view class="update-desc" v-if="!showProgress">
					<text>{{ updateDescription || '优化用户体验，修复已知问题' }}</text>
				</view>
				<!-- 下载进度 -->
				<view class="download-progress" v-if="showProgress">
					<view class="progress-bg">
						<view class="progress-fill" :style="{width: progress + '%'}"></view>
					</view>
					<text class="progress-text">当前进度: {{ progress }}%</text>
					<text class="progress-file-type">{{ updateUrl.endsWith('.apk') ? '应用更新包' : '热更新包' }}</text>
					<text class="progress-info">已下载: {{ downloadSize }} / {{ totalSize }}</text>
					<text class="progress-info">下载速度: {{ downloadSpeed }}</text>
				</view>
			</view>
			<!-- 底部按钮区域 -->
			<view class="popup-footer" v-if="!showProgress">
				<button class="update-btn" @click="handleUpdate">立即升级</button>
			</view>
		</view>
	</view>
</template>

<script>
export default {
	name: 'update-popup',
	props: {
		// 可选的传入版本号，如不传入则自动获取
		currentVersion: {
			type: String,
			default: ''
		}
	},
	data() {
		return {
			showUpdate: false,
			showProgress: false,
			latestVersion: '',
			updateUrl: '',
			updateDescription: '',
			progress: 0,
			isUpdating: false,
			realCurrentVersion: this.currentVersion || '1.0.0', // 实际使用的版本号
			downloadSize: '0 MB', // 已下载大小
			totalSize: '未知', // 总文件大小
			downloadSpeed: '0 KB/s' // 下载速度
		}
	},
	mounted() {
			// 组件挂载时获取应用版本号
			this.getAppVersion();
		},
	methods: {
		// 获取应用当前版本号
		getAppVersion() {
			try {
				// 在 uni-app 中使用 plus.runtime.version 获取应用版本号
				if (typeof plus !== 'undefined' && plus.runtime) {
					const appVersion = plus.runtime.version;
					this.realCurrentVersion = appVersion;
					console.log('获取到应用版本号:', appVersion);
				} else {
					// 在浏览器环境或 plus 未就绪时
					console.log('无法获取应用版本号，使用默认值');
				}
			} catch (error) {
				console.error('获取版本号失败:', error);
			}
			
			// 延迟一点再检查更新，确保版本号已获取
			setTimeout(() => {
				this.checkUpdate();
			}, 300);
		},
		
		// 检查更新
		checkUpdate() {
			
			// 获取配置的更新接口
			const updateUrl = 'https://qyapi.ipaybuy.cn/updateApp.json';
			
			uni.request({
				url: updateUrl,
				method: 'GET',
				success: (res) => {
					if (res.statusCode === 200 && res.data) {
						const { code, url, desc } = res.data;
						this.latestVersion = code;
						this.updateUrl = url;
						this.updateDescription = desc || '';
						console.log("最新版本：",code);
									// 比较版本号
						if (this.compareVersion(code, this.realCurrentVersion) > 0) {
							// 显示更新弹窗
							this.showUpdate = true;
						}
					}
				},
				fail: (err) => {
					console.error('检查更新失败:', err);
				}
			});
		},
		
		// 比较版本号
		compareVersion(version1, version2) {
			const v1 = version1.split('.').map(Number);
			const v2 = version2.split('.').map(Number);
			const maxLength = Math.max(v1.length, v2.length);
			
			for (let i = 0; i < maxLength; i++) {
				const num1 = v1[i] || 0;
				const num2 = v2[i] || 0;
				if (num1 > num2) return 1;
				if (num1 < num2) return -1;
			}
			return 0;
		},
		
		// 处理升级
		handleUpdate() {
			if (this.isUpdating) return;
			this.isUpdating = true;
			
			// 保持弹窗显示，切换为进度显示模式
			this.showProgress = true;
			this.progress = 0;
			this.downloadSize = '0 MB';
			this.totalSize = '未知';
			this.downloadSpeed = '0 KB/s';
			this.lastTime = null;
			this.lastBytes = 0;
			
			// 判断更新类型
			if (this.updateUrl.endsWith('.apk')) {
				this.updateApk();
			} else if (this.updateUrl.endsWith('.wgt')) {
				this.updateWgt();
			} else {
				uni.showToast({
					title: '不支持的更新文件格式',
					icon: 'none'
				});
				this.resetUpdateState();
			}
		},
		
		// APK更新
		updateApk() {
			// 下载APK文件
			const downloadTask = uni.downloadFile({
				url: this.updateUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						// 安装APK
						plus.runtime.install(res.tempFilePath, {}, () => {
							uni.showToast({
								title: '安装成功',
								icon: 'success'
							});
							this.resetUpdateState();
							// 提示用户重启应用
							uni.showModal({
									 title: '更新完成',
									 content: '应用已更新，请重启应用生效',
									 showCancel: false,
									 success: () => {
										 plus.runtime.quit();
									 }
								});
						}, (error) => {
							console.error('安装失败:', error);
							uni.showToast({
								title: '安装失败，请重试',
								icon: 'none'
							});
							this.resetUpdateState();
						});
					}
				},
				fail: (err) => {
					console.error('下载APK失败:', err);
					uni.showToast({
						title: '下载失败，请重试',
						icon: 'none'
					});
					this.resetUpdateState();
				}
			});
			
			// 监听下载进度
			downloadTask.onProgressUpdate((res) => {
				console.log("测试进度:", res.progress);
				console.log("已下载:", res.totalBytesWritten);
				console.log("总大小:", res.totalBytesExpectedToWrite);
				
				this.progress = res.progress;
				// 计算并显示下载大小和速度
				if (res.totalBytesExpectedToWrite) {
					this.totalSize = this.formatFileSize(res.totalBytesExpectedToWrite);
				}
				if (res.totalBytesWritten) {
					this.downloadSize = this.formatFileSize(res.totalBytesWritten);
				}
				// 计算下载速度
				if (this.lastTime && this.lastBytes) {
					const currentTime = Date.now();
					const timeDiff = (currentTime - this.lastTime) / 1000; // 秒
					const bytesDiff = res.totalBytesWritten - this.lastBytes;
					if (timeDiff > 0) {
						this.downloadSpeed = this.formatFileSize(bytesDiff / timeDiff) + '/s';
					}
				}
				// 记录当前状态
				this.lastTime = Date.now();
				this.lastBytes = res.totalBytesWritten;
			});
		},
		
		// WGT热更新
		updateWgt() {
			// 下载WGT文件
			const downloadTask = uni.downloadFile({
				url: this.updateUrl,
				success: (res) => {
					if (res.statusCode === 200) {
						// 安装WGT包
						plus.runtime.install(res.tempFilePath, {
							force: false
						}, () => {
							uni.showToast({
								title: '更新成功',
								icon: 'success'
							});
							this.resetUpdateState();
							// 提示用户重启应用
							uni.showModal({
									 title: '更新完成',
									 content: '应用已热更新，请重启应用生效',
									 showCancel: false,
									 success: () => {
										 plus.runtime.restart();
									 }
								});
						}, (error) => {
							console.error('热更新失败:', error);
							uni.showToast({
								title: '更新失败，请重试',
								icon: 'none'
							});
							this.resetUpdateState();
						});
					}
				},
				fail: (err) => {
					console.error('下载WGT失败:', err);
					uni.showToast({
						title: '下载失败，请重试',
						icon: 'none'
					});
					this.resetUpdateState();
				}
			});
			
			// 监听下载进度
			downloadTask.onProgressUpdate((res) => {
				console.log("WGT下载进度:", res.progress);
				console.log("已下载:", res.totalBytesWritten);
				console.log("总大小:", res.totalBytesExpectedToWrite);
				
				this.progress = res.progress;
				// 计算并显示下载大小和速度
				if (res.totalBytesExpectedToWrite) {
					this.totalSize = this.formatFileSize(res.totalBytesExpectedToWrite);
				}
				if (res.totalBytesWritten) {
					this.downloadSize = this.formatFileSize(res.totalBytesWritten);
				}
				// 计算下载速度
				if (this.lastTime && this.lastBytes) {
					const currentTime = Date.now();
					const timeDiff = (currentTime - this.lastTime) / 1000; // 秒
					const bytesDiff = res.totalBytesWritten - this.lastBytes;
					if (timeDiff > 0) {
						this.downloadSpeed = this.formatFileSize(bytesDiff / timeDiff) + '/s';
					}
				}
				// 记录当前状态
				this.lastTime = Date.now();
				this.lastBytes = res.totalBytesWritten;
			});
		},
		
		// 重置更新状态
		resetUpdateState() {
			this.isUpdating = false;
			this.showProgress = false;
			this.progress = 0;
			this.downloadSize = '0 MB';
			this.totalSize = '未知';
			this.downloadSpeed = '0 KB/s';
			this.lastTime = null;
			this.lastBytes = 0;
		},
		
		// 格式化文件大小
		formatFileSize(bytes) {
			if (bytes === 0) return '0 B';
			const k = 1024;
			const sizes = ['B', 'KB', 'MB', 'GB'];
			const i = Math.floor(Math.log(bytes) / Math.log(k));
			return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
		}
	}
}
</script>

<style scoped>
.update-popup {
	position: fixed;
	left: 0;
	top: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	flex-direction: column;
	justify-content: center;
	align-items: center;
}

.popup-content {
	width: 80%;
	background-color: #fff;
	border-radius: 20rpx;
	overflow: hidden;
}

.popup-header {
	padding: 30rpx;
	text-align: center;
	border-bottom: 1rpx solid #eee;
}

.popup-title {
	font-size: 36rpx;
	font-weight: bold;
	color: #333;
}

.popup-body {
	padding: 30rpx;
}

.version-info {
	display: flex;
	justify-content: space-between;
	margin-bottom: 20rpx;
}

.version-info text {
	font-size: 28rpx;
	color: #666;
}

.update-desc {
	font-size: 28rpx;
	color: #999;
	line-height: 44rpx;
}

.popup-footer {
	padding: 20rpx 30rpx 30rpx;
}

.update-btn {
	width: 100%;
	height: 80rpx;
	line-height: 80rpx;
	background-color: #007aff;
	color: #fff;
	border-radius: 40rpx;
	font-size: 32rpx;
}

.download-progress {
	width: 100%;
	padding: 20rpx 0;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.progress-bg {
	width: 100%;
	height: 20rpx;
	background-color: #eee;
	border-radius: 10rpx;
	overflow: hidden;
	margin-bottom: 10rpx;
}

.progress-fill {
	height: 100%;
	background-color: #007aff;
	border-radius: 10rpx;
	transition: width 0.3s;
}

.progress-text {
	display: block;
	text-align: center;
	font-size: 32rpx;
	color: #333;
	margin-top: 20rpx;
	font-weight: 500;
}

/* 进度标题现在直接使用弹窗标题，无需单独样式 */

.progress-file-type {
	font-size: 28rpx;
	color: #666;
	margin-top: 10rpx;
}

.progress-info {
	font-size: 26rpx;
	color: #888;
	margin-top: 8rpx;
}
</style>